layui.use(["zlContext"], function (exports) {
    var $ = layui.$
        , zlContext = layui.zlContext
        , layer = layui.layer
        , table = layui.table
        , form = layui.form
        , zlConfig = layui.zlConfig
        , statusName = zlConfig.global.result.statusName
        , msgName = zlConfig.global.result.msgName
        , dataName = zlConfig.global.result.dataName
        , OK = zlConfig.global.result.okState
        , fullheight = 'full-30'
        , loadingLayer
        , curHomepage = undefined;

    //加载首页页面内容
    loadingLayer = layer.msg('数据加载中，请稍候...', { icon: 16, time: false, shade: 0.1 });
    var homepageRwid = $.trim($('#homepage-rwid').val());
    if(homepageRwid){
        zlContext.asyncGet(layui.cache['contentPath'] + '/manager/corehomepage/querybyid', { 'RWID': homepageRwid}, function (result) {
            if (result[statusName] = OK) {
                curHomepage = result[dataName];
            } else {
                zlContext.errorMsg(result[msgName]);
            }
        }, false);
    }

    var options = {
        float: false,
        auto: true,
        always_show_resize_handle: false,
        disableDrag: true,
        disableResize: true
    };
    var frmTemplate = [
        '<div>'
        , '  <div class="grid-stack-item-content">'
        , '     <div class="grid-stack-item-header"><h5 class="item-title">标题</h5>'
        , '         <div class="grid-stack-item-operate">'
        , '             <button class="layui-btn layui-btn-primary layui-btn-sm edit-btn"><i class="layui-icon layui-icon-edit"></i></button>'
        , '             <button class="layui-btn layui-btn-primary layui-btn-sm del-btn"><i class="layui-icon layui-icon-delete"></i></button>'
        , '         </div>'
        , '     </div>'
        , '     <div class="grid-stack-item-body"></div>'
        , '  </div>'
        , '</div>'
    ];
    var defaultNode = {
        x: 0,
        y: 0,
        width: 4,
        height: 3
    }
    //渲染
    $('.grid-stack').gridstack(options);

    var gridstackAction = new function () {
        this.items = [];
        this.grid = $('.grid-stack').data('gridstack');

        //增加
        this.addNewWidget = function () {
            var node = this.items.pop() || {
                x: 0,
                y: 0,
                width: 3,
                height: 2
            };
            this.grid.addWidget($(frmTemplate.join("")),
                node.x, node.y, node.width, node.height);
            return false;
        }.bind(this);

        //清空
        this.clearGrid = function () {
            this.grid.removeAll();
            return false;
        }.bind(this);

        $('#add-new-widget').click(this.addNewWidget);

        $('.design-header #btn-clear').click(this.clearGrid);

        $('.design-header #btn-save').click(this.saveGrid);
    }

     //权限过滤
    if (curHomepage && curHomepage['HP_CONTENT']) {
        var homepageContent = [];
        try {
            homepageContent = JSON.parse(curHomepage['HP_CONTENT']);
            var resAnthMap = curHomepage['RESAUTHMAP'] || {};
            var noAuthTemplate = [
                 '<div class="empty-data" style="text-align:center;padding-top: 20px;font-size: 25px;color: #ccc;font-family: tahoma ,微软雅黑;">'
                ,'  <div style="padding-top: 10px;font-size: 22px;">无权限访问</div>'
                ,'</div>'
            ];
            var arrContent = [];
            $.each(homepageContent, function(i, node){
                var rwid = node['zlRwid'];
                var titleName = node['titleName'] || '标题';
                var $item = $(frmTemplate.join(''));
                node['locked'] = true;
                node['noMove'] = true;
                node['noResize'] = true;
                $item.attr('data-gs-locked', node.locked); 
                $item.attr('data-gs-no-move', node.noMove); 
                $item.attr('data-gs-no-resize', node.noResize); 
                $item.find('.grid-stack-item-content').attr('data-zl-rwid', rwid);
                $item.find('.grid-stack-item-header .item-title').text(titleName);
                if(node['isshow']=='0'){
                    $item.find('.grid-stack-item-header').hide();
                    $item.find('.grid-stack-item-body').css('top',0);
                }
                //权限判断
                var action = resAnthMap[rwid];
                var $itemBody = undefined;
                if(action && action != '1'){
                   var url = action.replace(/#{contentpath}/i, layui.cache['contentPath']);
                   $itemBody = $('<iframe src="' + getTokenIdUrl(url) + '" width=100% height=100% frameborder=”no” border=”0″ marginwidth=”0″ marginheight=”0″ scrolling=”no” allowtransparency=”yes”></iframe>');
                } else{
                    $itemBody = $(noAuthTemplate.join(''));
                    if("1" == action){
                        $itemBody.find('.no-data-show').text('无效模块');
                    }
                }
                if (node['isshow'] == '0') {
                    $item.find('.grid-stack-item-body').css("height", "100%");
                } else {
                    $item.find('.grid-stack-item-body').css("height", "calc(100% - 41px)");
                }
                
                $item.find('.grid-stack-item-body').append($itemBody);
                gridstackAction.grid.addWidget($item, node['x'], node['y'], node['width'],node['height'], 
                    node['autoPosition'], node['minWidth'], node['maxWidth'], node['minHeight'], node['maxHeight'], node['id']);
            });
        } catch (error) {
            zlContext.errorMsg("数据加载异常！！");
        }
    }

    $(".grid-stack").css({ "height": $(window).height() - 63, "min-height": $(window).height() - 140 });
    layer.close(loadingLayer);
    // z自适应控制页面高度
    $(window).resize(function () {
        var height = $(window).height() - 63;
        $("body").css("min-height", $(window).height() - 90);
        $(".grid-stack").css({ "height": height, "min-height": $(window).height() - 140 });
    });
});